package com.yaozheng.vocationaltraining.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.adapter.MeQuestionsEncyclopediaAdapter;
import com.yaozheng.vocationaltraining.adapter.RewardGridViewAdapter;
import com.yaozheng.vocationaltraining.bean.CategoriesBean;
import com.yaozheng.vocationaltraining.bean.HundredQuestionsEncyclopediaItemBean;
import com.yaozheng.vocationaltraining.bean.RewardBean;
import com.yaozheng.vocationaltraining.dialog.userinfo.ListViewSelectDialog;
import com.yaozheng.vocationaltraining.iview.IAddQuestionsView;
import com.yaozheng.vocationaltraining.manage.ListViewLoadMoreManage;
import com.yaozheng.vocationaltraining.service.AddQuestionsService;
import com.yaozheng.vocationaltraining.service.HundredQuestionsEncyclopediaService;
import com.yaozheng.vocationaltraining.service.impl.AddQuestionsServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.HundredQuestionsEncyclopediaServiceImpl;
import com.yaozheng.vocationaltraining.utils.Config;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.utils.Utils;
import com.yaozheng.vocationaltraining.view.ActionSheetDialog;
import com.yaozheng.vocationaltraining.view.ExpandGridView;
import com.yaozheng.vocationaltraining.view.userinfo.ListViewSelectDialogView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.apache.commons.collections.ArrayStack;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by moon on 2017/11/9.
 */

@EActivity(R.layout.activity_add_questions)
public class AddQuestionsActivity extends BaseActivity
        implements IAddQuestionsView {
    String fileName;
    String dirPath;
    private String oriFilePath;
    private static final int PHOTO_GRAPH = 1;//
    private static final int SELECT_IMAGE = 2;

    @ViewById
    ImageView headBackImage;
    @ViewById
    TextView headLeftTextView;
    @ViewById
    TextView headRightText;

    @ViewById
    ExpandGridView reward_gridview;
    RewardGridViewAdapter rewardAdapter;
    ArrayList<RewardBean> rewardData = new ArrayList<>();

    @ViewById
    LinearLayout reward_layout;

    @ViewById
    LinearLayout add_reward_layout;

    @ViewById
    TextView reward_num_textview;

    @ViewById
    ImageView reward_image;

    @ViewById
    ImageView attachment_imageview;
    @ViewById
    TextView delete_textview;

    @ViewById
    EditText title_edittext;
    @ViewById
    EditText body_edittext;

    @ViewById
    TextView quarter_textview;

    @ViewById
    TextView input_title_lenght_textview;

    @ViewById
    Spinner spinner;
    private ArrayAdapter spinnerAdapter;

    @Bean(AddQuestionsServiceImpl.class)
    AddQuestionsService addQuestionsService;

    LayoutInflater inflater;

    String imagePath;

    ArrayList<CategoriesBean> categorues;
    int categoryId=1;

    @AfterViews
    public void initView() {
        setHeadTitle("提问");
        inflater = this.getLayoutInflater();

        addQuestionsService.init(this);

        headBackImage.setVisibility(View.GONE);
        headLeftTextView.setVisibility(View.VISIBLE);
        headRightText.setVisibility(View.VISIBLE);
        headRightText.setTextColor(this.getResources().getColor(R.color.footer_bg_color));
        headLeftTextView.setText("取消");
        headRightText.setText("提交");

        loadCategoriesData();
        loadScore();


        rewardAdapter = new RewardGridViewAdapter(this,rewardData);
        reward_gridview.setAdapter(rewardAdapter);
        reward_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(rewardData.get(i).isAvailable()){
                    rewardAdapter.setselectedPosition(i);
                    reward_layout.setVisibility(View.GONE);

                    reward_num_textview.setVisibility(View.VISIBLE);
                    reward_num_textview.setText(rewardData.get(i).getScore()+"");

                    reward_image.setVisibility(View.GONE);
                }
            }
        });

        title_edittext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
        title_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                if(title_edittext.getEditableText().toString().length() >= 50){
//                    return;
//                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                input_title_lenght_textview.setText(title_edittext.getEditableText().toString().length()+"");
            }
        });


        loadRewardData();
        //onRefresh();


    }

    private void loadScore() {
        addQuestionsService.loadScore();
    }

    @Click(R.id.add_reward_layout)
    public void OpenRewardView(){
        reward_layout.setVisibility(View.VISIBLE);
    }

    @Click(R.id.headLeftTextView)
    public void headLeftTextClick(){
        finish();
    }

    @Click(R.id.delete_textview)
    public void deleteTextviewClick(){
        imagePath = "";
        attachment_imageview.setVisibility(View.GONE);
        attachment_imageview.setImageURI(null);

        delete_textview.setVisibility(View.GONE);
    }



    @Click(R.id.headRightText)
    public void headRightTextClick(){
        if (TextUtils.isEmpty(title_edittext.getEditableText().toString())){
            Toast.makeText(this,"标题不能为空!",Toast.LENGTH_SHORT).show();
            return;
        }
        showOperatingProgressDialog("发布中。。。");
        addQuestionsService.addQuestion(categoryId, //TODO
                title_edittext.getEditableText().toString(),
                imagePath,
                body_edittext.getEditableText().toString(),
                reward_num_textview.getText().toString());

    }

    private void loadCategoriesData() {
        addQuestionsService.loadCategories();
    }

    ListViewSelectDialog listSelectDialog;
    /**
     * 相册
     */
    public static final String[] PHOTO_GALLERY_STR = new String[]{"拍照上传", "从相册选取"};
    JSONArray  photoGalleryJsonArray;
    File sourceFile;
    @Click(R.id.add_phote)
    public void showSelectPhoteTypeDialog() {
        photoGalleryJsonArray = ListViewSelectDialogView.stringArrayToJsonArray(PHOTO_GALLERY_STR);
        if (listSelectDialog == null) {
                listSelectDialog = new ListViewSelectDialog(this);
        }
        listSelectDialog.show();
        ListViewSelectDialogView listViewSelectDialogView = listSelectDialog.getListViewSelectDialogView();
        listViewSelectDialogView.setTitle("请选择");
        listViewSelectDialogView.setListViewSelectDialogViewItemClick(new ListViewSelectDialogView.ListViewSelectDialogViewItemClick() {
            @Override
            public void itemClick(int position) {
                photoGallerySelect(position);
            }
        });
        listViewSelectDialogView.setDataList(photoGalleryJsonArray);



//        new ActionSheetDialog(AddQuestionsActivity.this)
//                .builder()
//                .setCancelable(true)
//                .setCanceledOnTouchOutside(true)
//                .addSheetItem("拍照上传", ActionSheetDialog.SheetItemColor.Blue,
//                        new ActionSheetDialog.OnSheetItemClickListener() {
//
//                            @Override
//                            public void onClick(int which) {
//                                if (Environment.getExternalStorageState()
//                                        .equals(Environment.MEDIA_MOUNTED)) {
//                                    fileName = Utils.getFileName();
//                                    dirPath = Environment
//                                            .getExternalStorageDirectory()
//                                            .getPath()
//                                            + Config.getSavePath();
//                                    File tempFile = new File(dirPath);
//                                    if (!tempFile.exists()) {
//                                        tempFile.mkdirs();
//                                    }
//                                    File saveFile = new File(tempFile, fileName
//                                            + ".jpg");
//                                    Intent intent = new Intent(
//                                            MediaStore.ACTION_IMAGE_CAPTURE);
//                                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
//                                            Uri.fromFile(saveFile));
//                                    startActivityForResult(intent, PHOTO_GRAPH);
//                                } else {
//                                    Toast.makeText(AddQuestionsActivity.this,
//                                            "未检测到CDcard，拍照不可用!",
//                                            Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        })
//                .addSheetItem("从图库中选择", ActionSheetDialog.SheetItemColor.Blue,
//                        new ActionSheetDialog.OnSheetItemClickListener() {
//
//                            @Override
//                            public void onClick(int which) {
//                                fileName = Utils.getFileName();
//                                Intent i = new Intent(Intent.ACTION_PICK, android.
//                                        provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                                startActivityForResult(i, SELECT_IMAGE);
//                            }
//                        }).show();
    }

    /**
     * 相册选择
     *
     * @param position 0 "拍头像",  1 "从相册选取"
     */
    public void photoGallerySelect(int position) {
        if (listSelectDialog != null && listSelectDialog.isShowing()) {
            listSelectDialog.cancel();
        }
        if (position == 0) {
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);

            intent.putExtra(
                    MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(
                            Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                            getString(R.string.cutOutPhotoSnapName))));
            startActivityForResult(intent, Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE);
        } else if (position == 1) {
              /*
                             * 从相册选取
							 */
            Intent intent = new Intent(
                    "android.intent.action.PICK");
            intent.setDataAndType(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    "image/JPEG");
//            intent.putExtra(
//                    "output",
//                    Uri.fromFile(new File(
//                            Environment
//                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
//                            getString(R.string.cutOutPhotoSnapName))));
//            intent.putExtra("crop", "true");
//            intent.putExtra("aspectX", 1);// 裁剪框比例
//            intent.putExtra("aspectY", 1);
//            intent.putExtra("outputX",
//                    getString(R.string.outputX));// 输出图片大小
//            intent.putExtra("outputY",
//                    getString(R.string.outputY));
            // intent.
            startActivityForResult(intent, Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

            if(data == null){ //拍照过来的

               File imageFile = new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                        getString(R.string.cutOutPhotoSnapName));

                imagePath = imageFile.getAbsolutePath();
                attachment_imageview.setVisibility(View.VISIBLE);
                attachment_imageview.setImageURI(Uri.fromFile(imageFile));

                delete_textview.setVisibility(View.VISIBLE);

                //剪切图片
//                cutOutImage(Environment
//                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+
//                        getString(R.string.cutOutPhotoSnapName));
            }else{ //相册过来的
                Uri selectedImage = data.getData();
                imagePath = selectedImage.getPath();
                attachment_imageview.setVisibility(View.VISIBLE);
                attachment_imageview.setImageURI(selectedImage);
                delete_textview.setVisibility(View.VISIBLE);

//
//                cutOutImage(picturePath);
            }

        } else if (resultCode == Activity.RESULT_OK && requestCode == Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE) {
            //提交图片

            onCutOutPhotoStyemtActivityResult(requestCode, resultCode, data);
        } else {
            super.
                    onActivityResult(requestCode, resultCode, data);
        }

//        if (requestCode == PHOTO_GRAPH && resultCode == Activity.RESULT_OK) {
//            Intent intent = new Intent();
//            intent.putExtra(Config.KEYPATH, dirPath + "/" + fileName + ".jpg");
//
//            attachment_imageview.setVisibility(View.VISIBLE);
//            attachment_imageview.setImageURI(Uri.fromFile(new File(dirPath + "/"
//                    + fileName + ".jpg")));
//            oriFilePath = dirPath + "/" + fileName + ".jpg";
//        } else if (requestCode == SELECT_IMAGE
//                && resultCode == Activity.RESULT_OK) {
//            Uri selectedImage = data.getData();
//            String[] filePathColumn = { MediaStore.Images.Media.DATA };
//
//            Cursor cursor = getContentResolver().query(selectedImage,
//                    filePathColumn, null, null, null);
//            cursor.moveToFirst();
//
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            String picturePath = cursor.getString(columnIndex);
//            cursor.close();
//
//            attachment_imageview.setImageURI(Uri.fromFile(new File(picturePath)));
//            attachment_imageview.setVisibility(View.VISIBLE);
//            oriFilePath = picturePath;
//        }
    };

    /**
     * 剪切图片
     */
    public void cutOutImage(String filePath) {
        if (sourceFile != null && sourceFile.exists()) {
            sourceFile.delete();
        }

        File cutOutPhotoSnapFile = new File(filePath);
        //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(cutOutPhotoSnapFile),
                "image/JPEG");
        intent.putExtra(
                "output",
                Uri.fromFile(new File(
        Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                getString(R.string.attachment_image_path))));
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", getString(R.string.outputX));
//        intent.putExtra("outputY", getString(R.string.outputY));

        startActivityForResult(intent, Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE);
    }

    /**
     * 选择相册返回结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onCutOutPhotoStyemtActivityResult(int requestCode, int resultCode,
                                                  Intent data) {
        sourceFile = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                getString(R.string.attachment_image_path));

        attachment_imageview.setVisibility(View.VISIBLE);
        attachment_imageview.setImageURI(Uri.fromFile(sourceFile));
        delete_textview.setVisibility(View.VISIBLE);
//        showOperatingProgressDialog("上传中。。。");
//        myUserInfoService.uploadAvatar(sourceFile.getAbsolutePath());
    }

    private void loadRewardData() {
        addQuestionsService.loadRewardData();
    }

    @Override
    public void rewardDataSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","awards");
            if (dataList != null) {

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    RewardBean bean = new RewardBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setScore(jsonObject2.getInt("score"));
                    bean.setStatus(jsonObject2.getInt("status"));
                    bean.setAvailable(jsonObject2.getBoolean("available"));

                    rewardData.add(bean);
                }

                rewardAdapter.setData(rewardData);
                rewardAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @Override
    public void rewardDataError(String error) {

    }

    @UiThread
    @Override
    public void addQuestionSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        Toast.makeText(this,"添加问题成功!",Toast.LENGTH_SHORT).show();
        finish();
    }

    @UiThread
    @Override
    public void addQuestionError(String error) {
        cancelOperatingProgressDialog();
        Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void categoriesListSuccess(JSONObject jsonObject) {
        JSONArray categoriesList = TypeUtils.getJsonArray(jsonObject,"data",
                "categories");

        categorues = new ArrayList<>();

        for (int i = 0; i < categoriesList.size(); i++) {
            JSONObject jsonObject2 = categoriesList.getJSONObject(i);

            CategoriesBean bean = new CategoriesBean();
            bean.setId(jsonObject2.getInt("id"));
            bean.setActiveIcon(jsonObject2.getString("activeIcon"));
            bean.setIcon(jsonObject2.getString("icon"));
            bean.setName(jsonObject2.getString("name"));
            categorues.add(bean);
        }

        //将可选内容与ArrayAdapter连接起来
//        spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.question_type, R.layout.spinner_item);

        spinnerAdapter = new ArrayAdapter<CategoriesBean>(this, R.layout.spinner_item, categorues);

        //设置下拉列表的风格
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter2 添加到spinner中
        spinner.setAdapter(spinnerAdapter);

        //添加事件Spinner事件监听
        spinner.setOnItemSelectedListener(new SpinnerXMLSelectedListener());
    }

    @UiThread
    @Override
    public void categoriesListError(String error) {

    }

    @UiThread
    @Override
    public void loadScoreSuccess(JSONObject jsonObject) {
        JSONObject scoreObject = TypeUtils.getJsonObject(jsonObject,"data","score");
        int quarter = scoreObject.getInt("quarter");
        quarter_textview.setText(quarter+"");
    }

    @UiThread
    @Override
    public void loadScoreError(String error) {

    }

    //使用XML形式操作
    class SpinnerXMLSelectedListener implements AdapterView.OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> adapterView, View view, int position,
                                   long arg3) {
            //text.setText("你使用什么样的手机："+spinnerAdapter.getItem(position));
            categoryId = categorues.get(position).getId();
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }

    }

    @Override
    public void responseSuccess(JSONObject jsonObject) {

    }

    @Override
    public void responseError(String error) {

    }
}
